<?php
namespace common\queue\jobs;

use common\bot\LoginService;
use common\model\sell66\Bot;
use think\queue\Job;
use common\queue\JobAbstract;
use think\Log;


class LoginBot extends JobAbstract{

    public function loginBot(Job $job, $botId){
        if($botId < 0){
            $job->delete();
        }
        try {
            $botConfig = Bot::getOneBotSettings($botId);
            if(empty($botConfig)){
                throw new \Exception('无机器人'.$botId.'配置');
            }
            echo 'login_bot: '.$botId. ' start';
            $robot = LoginService::getInstance()->dologin($botConfig);
            if($robot){
                echo 'login_bot: '.$botId. ' is success';
                $job->delete();
            }else{
                throw new \Exception('机器人'.$botId.'登录失败');
            }
        } catch (\Exception $e) {
            echo 'login_bot: '.$botId. ' is fail';
            $job->delete();
            $data['desc'] = '登录机器人失败';
            $data['exception'] = $e->getMessage();
            $this->failed($data);
        }

    }


    public function failed($data,$source=''){
        switch ($source){
            case 'login_bot':
                $path = APP_PATH . '../runtime/logs/bot/loginBot/';
                break;
            default:
                $path = APP_PATH . '../runtime/logs/bot/error/';
                break;
        }
        Log::init(['type' => 'File', 'path' => $path]);
        Log::write('login bot failed:'.json_encode($data));
    }

}
